import Vue from 'vue'
import VueRouter from 'vue-router'
import LoginComponent from '@/components/login-component.vue'
import HomeComponent from '@/components/home-component.vue'
import WelcomeComponent from '@/components/welcome-component.vue'
import UsersTemplate from '@/components/user/users-template.vue'
import RightsTemplate from '@/components/power/rights-template.vue'
import RolesTemplate from '@/components/power/roles-template.vue'
import CateTemplate from '@/components/goods/cate-template.vue'
import GoodsParamsTemplate from '@/components/goods/goods_params_template.vue'
import ReportTemplate from '@/components/report/report-template.vue'

Vue.use(VueRouter)

const routes = [
  // 路由重定向,自动跳转到login组件
  { path: '/', redirect: '/login' },
  { path: '/login', component: LoginComponent },
  {
    path: '/home',
    component: HomeComponent,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: WelcomeComponent },
      { path: '/users', component: UsersTemplate },
      { path: '/rights', component: RightsTemplate },
      { path: '/roles', component: RolesTemplate },
      { path: '/categories', component: CateTemplate },
      { path: '/params', component: GoodsParamsTemplate },
      { path: '/reports', component: ReportTemplate }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 挂在路由导航守卫, 控制页面跳转权限
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数， 表示放行
  // next() 放行      next('/login') 强制跳转

  if (to.path === '/login') return next()
  // 获取token
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()
})

export default router
